import {_decorator, Component, resources, TextAsset} from 'cc';

const {ccclass, property} = _decorator;

@ccclass('CSVReader')
export class CSVReader extends Component {

    /**
     * 读取CSV文件并转换为对象数组
     * @param path resources文件夹下的相对路径（不包含后缀）
     * @returns 包含每行数据的对象数组
     */
    public static readCSVToArray(path: string): { [key: string]: string }[] {
        resources.preload('new-world-configs/' + path, TextAsset);
        const textAsset = resources.get('new-world-configs/' + path, TextAsset)
        if (!textAsset) {
            return []
        }
        try {
            return this.parseCSV(textAsset.text)
        } catch (parseError) {
            console.error('解析CSV失败:', parseError);
            return [];
        }
    }

    /**
     * 解析CSV文本内容
     * @param csvText CSV文件内容
     * @returns 解析后的对象数组
     */
    private static parseCSV(csvText: string): { [key: string]: string }[] {
        const lines = csvText.split('\n').filter(line => line.trim() !== '');

        if (lines.length === 0) {
            return [];
        }

        // 解析标题行
        const headers = this.parseCSVLine(lines[1]);

        const result: { [key: string]: string }[] = [];

        // 解析数据行
        for (let i = 3; i < lines.length; i++) {
            const values = this.parseCSVLine(lines[i]);

            if (values.length !== headers.length) {
                console.warn(`第${i + 1}行列数不匹配，跳过该行`);
                continue;
            }

            const rowObject: { [key: string]: string } = {};
            for (let j = 0; j < headers.length; j++) {
                rowObject[headers[j].trim()] = values[j].trim();
            }

            result.push(rowObject);
        }

        return result;
    }

    /**
     * 解析单行CSV数据，处理引号和逗号
     * @param line CSV单行数据
     * @returns 解析后的字段数组
     */
    private static parseCSVLine(line: string): string[] {
        const result: string[] = [];
        let current = '';
        let inQuotes = false;
        let quoteChar = '"';

        for (let i = 0; i < line.length; i++) {
            const char = line[i];

            if (char === quoteChar) {
                inQuotes = !inQuotes;
            } else if (char === ',' && !inQuotes) {
                result.push(current);
                current = '';
            } else {
                current += char;
            }
        }

        // 添加最后一个字段
        result.push(current);

        return result;
    }
}